import { Service } from 'egg';
// const fs = require('fs');

/**
 * Test Service
 */
const { Op, cast, col } = require("sequelize");
export default class goods extends Service {
  public async addGoods(req) {
    const { user_id, title, category, price, contact, address, content, images, latitude, longitude } = req;
    let arr: any = [];
    let array = images.split('@');
    for (let i = 0; i < array.length; i++) {
      arr[i] = await this.ctx.helper.writeImage(array[i])
    }
    let res = await this.ctx.model.Goods.create({
      user_id,
      title,
      category,
      price,
      contact,
      address,
      content,
      longitude,
      latitude,
      imgs: arr.toString()
    })
    if (res) {
      return res
    } else {
      throw new Error()
    }
  }

  public async updateGoods(req) {
    const { goods_id, title, category, price, contact, address, content, images, oldImgs, latitude, longitude } = req;
    let arr: any = [];
    if (images !== '') {
      let array = images.split('@');
      for (let i = 0; i < array.length; i++) {
        arr[i] = await this.ctx.helper.writeImage(array[i])
      }
    }
    let oldimg = oldImgs.split(',');
    arr = [...oldimg, ...arr];
    let res = await this.ctx.model.Goods.update({
      title,
      category,
      price,
      contact,
      address,
      content,
      longitude,
      latitude,
      imgs: arr.toString()
    }, {
      where: {
        id: goods_id
      }
    })
    if (res) {
      return res
    } else {
      throw new Error()
    }
  }

  public async delGoods(req) {
    let res = await this.ctx.model.Goods.destroy({
      where: {
        id: req.goods_id,
      }
    })
    if (res) {
      return res
    } else {
      throw new Error()
    }
  }

  public async getProductList(req) {
    console.log(req);
    let res;
    console.log(req.user_id);
    
    if (req.user_id !== 'null') {
      // 获取个人所有的商品
      res = await this.ctx.model.Goods.findAll({
        where: {
          user_id: req.user_id
        },
        offset: Number((req.pageCurrent - 1) * req.pageSize),
        limit: Number(req.pageSize)
      });
      return res
    } else {
      switch (req.category) {
        // 选择所有的商品排序
        case 'all':
          if (req.sort == 2) {
            // 价格排序商品列表
            res = await this.ctx.model.Goods.findAll({
              order: [
                // [goods, 'price', 'ASC']
                // [sequelize.cast(sequelize.col('code'), 'SIGNED'), 'DESC']
                [cast(col('price'), 'FLOAT'), 'ASC']
              ],
              where: {
                [Op.or]: [
                  { title: { [Op.like]: `%${req.search || ''}%` } },
                  { content: { [Op.like]: `%${req.search || ''}%` } },
                ],
              },
              offset: Number((req.pageCurrent - 1) * req.pageSize),
              limit: Number(req.pageSize)
            });
          } else if (req.sort == 1) {
            // 热度排序列表
            res = await this.ctx.model.Goods.findAll({
              order: [
                [goods, 'heat', 'DESC']
              ],
              where: {
                [Op.or]: [
                  { title: { [Op.like]: `%${req.search || ''}%` } },
                  { content: { [Op.like]: `%${req.search || ''}%` } },
                ],
              },
              offset: Number((req.pageCurrent - 1) * req.pageSize),
              limit: Number(req.pageSize)
            });
          } else {
            // 最新发布排序
            res = await this.ctx.model.Goods.findAll({
              order: [
                [goods, 'created_at', 'DESC']
              ],
              where: {
                // name: 'cheny', // 精确查询
                // mobile_no: {
                //   // 模糊查询单个字段
                //   [Op.like]:'%' +mobile_no + '%'
                // }
                [Op.or]: [
                  { title: { [Op.like]: `%${req.search || ''}%` } },
                  { content: { [Op.like]: `%${req.search || ''}%` } },
                ],
              },
              offset: Number((req.pageCurrent - 1) * req.pageSize),
              limit: Number(req.pageSize)
            });
          }
          break;
        default:
          if (req.sort == 1) {
            res = await this.ctx.model.Goods.findAll({
              order: [
                [goods, 'heat', 'DESC']
              ],
              where: {
                category: req.category,
                [Op.or]: [
                  { title: { [Op.like]: `%${req.search || ''}%` } },
                  { content: { [Op.like]: `%${req.search || ''}%` } },
                ],
              },
              offset: Number((req.pageCurrent - 1) * req.pageSize),
              limit: Number(req.pageSize)
            })
          } else if (req.sort == 2) {
            res = await this.ctx.model.Goods.findAll({
              order: [
                // [goods, 'price', 'ASC']
                // [cast(col('price'), 'SIGNED'), 'ASC']
                [cast(col('price'), 'FLOAT'), 'ASC']
              ],
              where: {
                category: req.category,
                [Op.or]: [
                  { title: { [Op.like]: `%${req.search || ''}%` } },
                  { content: { [Op.like]: `%${req.search || ''}%` } },
                ],
              },
              offset: Number((req.pageCurrent - 1) * req.pageSize),
              limit: Number(req.pageSize)
            });
          } else {
            res = await this.ctx.model.Goods.findAll({
              order: [
                [goods, 'created_at', 'DESC']
              ],
              where: {
                category: req.category,
                [Op.or]: [
                  { title: { [Op.like]: `%${req.search || ''}%` } },
                  { content: { [Op.like]: `%${req.search || ''}%` } },
                ],
              },
              offset: Number((req.pageCurrent - 1) * req.pageSize),
              limit: Number(req.pageSize)
            });
          }
          break;
      }
    }
    return res
  }

  public async getGoods(req) {
    let res = await this.ctx.model.Goods.findOne({
      where: {
        id: req.goods_id
      }
    })
    if (res) {
      return res
    } else {
      throw new Error()
    }
  }

  public async getFavorites(req) {
    let res1 = await this.ctx.model.Collection.findAll({
      where: {
        user_id: req.user_id
      }
    })
    let arr: any = [];
    for (let i = 0; i < res1.length; i++) {
      arr.push(res1[i].dataValues.goods_id);
    }
    let res2 = await this.ctx.model.Goods.findAll({
      where: {
        id: {
          [Op.in]: arr,
        }
      }
    })
    console.log(res2);

    if (res2) {
      return res2
    } else {
      throw new Error()
    }
  }

}